package com.shadow.bus.login;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.graphics.drawable.VectorDrawableCompat;
import android.view.View;
import android.widget.ImageView;

import com.shadow.bus.config.ItemFiled;
import com.shadow.bus.config.NetState;
import com.shadow.bus.config.ServiceUrl;
import com.shadow.bus.config.SpKey;
import com.shadow.bus.entity.LoginEntity;
import com.shadow.bus.event.LoadMainEvent;
import com.tepth.shadow.ui.dialog.sweet.DialogDelegate;
import com.tepth.shadow.ui.dialog.sweet.SweetAlertDialogDelegate;
import com.tepth.shadow.ui.recycler.MultipleItemEntity;
import com.tepth.shadow.ui.search.ClearEditText;
import com.zhangyu.shadow.core.account.AccountManager;
import com.zhangyu.shadow.core.delegate.RxShadowDelegate;
import com.zhangyu.shadow.core.net.callback.IError;
import com.zhangyu.shadow.core.net.callback.ISuccess;
import com.zhangyu.shadow.core.net.rx.RxRestClient;
import com.zhangyu.shadow.core.util.storage.ShadowPreference;
import com.zhangyu.shadow.core.util.toast.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import busfix.tepth.com.shadow_bus.R;
import busfix.tepth.com.shadow_bus.R2;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author zhangyu
 * @date 2018/7/2
 */

public class LoginDelegate extends RxShadowDelegate {
    public static LoginDelegate newInstance() {
        Bundle args = new Bundle();
        LoginDelegate fragment = new LoginDelegate();
        fragment.setArguments(args);
        return fragment;
    }

    @BindView(R2.id.login_edtId)
    ClearEditText mEditTextAccount;
    @BindView(R2.id.login_edtPwd)
    ClearEditText mEditTextPwd;
    @BindView(R2.id.iv_user)
    ImageView mIvUser;
    DialogDelegate mDialogDelegate;

    @Override
    public Object setLayout() {
        return R.layout.delegate_login;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        VectorDrawableCompat mDrawableUser = VectorDrawableCompat.create(getResources(),
                R.drawable.ic_account_circle_blue_24dp, _mActivity.getTheme());
        mIvUser.setImageDrawable(mDrawableUser);
        mDialogDelegate = new SweetAlertDialogDelegate(_mActivity);
        mEditTextAccount.setText(ShadowPreference.getCustomAppProfile(SpKey.ACCOUNT));
        mEditTextPwd.setText(ShadowPreference.getCustomAppProfile(SpKey.PASSWORD));
    }

    @OnClick(R2.id.login_btnLogin)
    public void onLogin() {
        final String account = mEditTextAccount.getText().toString();
        final String password = mEditTextPwd.getText().toString();
        if (account.isEmpty() || password.isEmpty()) {
            ToastUtils.showToast(getContext(), "请输入正确的用户名密码!");
        } else {
            final DialogDelegate delegate = new SweetAlertDialogDelegate(getContext());
            delegate.showProgressDialog(false, "正在登录...");

            if (!NetState.IS_NET_CONNECT) {
                delegate.stopProgressWithFailed("登录失败!", "当前网络连接不可用!");
            } else {
                mDisposables.add(RxRestClient.builder()
                        .url(ServiceUrl.USER_LOGIN)
                        .success(new ISuccess() {
                            @Override
                            public void onSuccess(String response) {
                                LoginDataConverter dataConverter = new LoginDataConverter();
                                dataConverter.setJsonData(response);
                                List<MultipleItemEntity> list = dataConverter.convert();
                                if (list != null && !list.isEmpty()) {
                                    LoginEntity loginEntity = list.get(0).getField(ItemFiled.ITEM_OBJ);
                                    ShadowPreference.addCustomAppProfile(SpKey.ACCOUNT, account);
                                    ShadowPreference.addCustomAppProfile(SpKey.PASSWORD, password);
                                    ShadowPreference.addCustomAppProfile(SpKey.TOKEN, loginEntity.getAuthKey());
                                    ShadowPreference.addCustomAppObj(SpKey.USER, loginEntity);
                                    AccountManager.setSignState(true);
                                    EventBus.getDefault().post(new LoadMainEvent());
                                    delegate.clearDialog();
                                } else {
                                    delegate.stopProgressWithFailed("登录失败", "服务器返回数据为空!");
                                }
                            }
                        })
                        .error(new IError() {
                            @Override
                            public void onError(int code, String msg) {
                                delegate.stopProgressWithFailed("登录失败", msg);
                            }
                        })
                        .params("loginName", account)
                        .params("password", password)
                        .build()
                        .get());
            }
        }

    }
}
